define(['utils', 'photoswipe', '../libs/getbg'], function(utils, photoswipe, getbg){
    function getTitle(str) {
      str = str || '';
      return /[\u4e00-\u9fa5]/.test(str) ? str.substr(-2) : str.substr(0, 2);
    }


    function pageLogic(config){
      this.pageview = config.pageview;
      this.rowInstance = this.pageview.showPageParams.rowInstance;

      this.type = this.pageview.showPageParams.type?this.pageview.showPageParams.type:0; //type=1为回复,type=2为赞
      this.data = this.rowInstance.datasource;


      this.userInfo = this.pageview.pageManager.userInfo;

      // console.log(this.data);
      // console.log(this.rowInstance.refs.form_content.$el);
      this.isAdmin = this.pageview.pageManager.userInfo.is_admin === 1;
      this.isMY = this.pageview.pageManager.userInfo.id === this.data.user_id;
    }
    pageLogic.prototype = {
      header_title_init:function(sender, params){
          sender.config.text = this.data.templateName;
      },

      header_edit_init:function(sender){
        if(!this.isMY){
          sender.config.style.display = "none";
        }
        if(this.isAdmin){
            //管理员有删除日志权限
            sender.config.style.display = "block";
        }
      },
      edit_btn_init:function(sender, params){
          //管理员不能编辑
          if(!this.isMY && this.isAdmin){
              sender.config.style.display = "none";
          }
      },
      avatar_init:function(sender, params){
        sender.config.src = this.data.avatar;
        sender.config.title = this.data.userName;
        if (sender.config.src === "./imgs/header.png") {
            sender.config.src="";
        } else {
            sender.config.defaultSrc = sender.config.src;
            sender.config.src = sender.config.src + ".thumb.jpg";
        }
      },
      user_name_init:function(sender, params){
        sender.config.text = this.data.userName;
      },
      atPersons_init:function(sender, params){

        if(this.data.at.length>0){
          sender.config.text = this.data.atStr;
        }else{
          sender.config.style.display = "none";
        }

      },
      position_init: function(sender, params) {
        var location = this.data.location||"";
        if(location.length===0){
          sender.config.style.display = "none";
          return;
        }
        sender.config.text = this.data.location;
      },
      segment_title_didmount:function (sender) {
           if(sender.datasource.label==="赞"){
               if(this.type===2){
                   window.setTimeout(function () {
                       sender.$el[0].click();
                       sender.$el.closest('.main-box').parent()[0].scrollTop = 10000000000;
                   },200);
               }

           }else if(sender.datasource.label==="回复"){
               if(this.type===1){
                   this.pageview.delegate("comment_textarea",function(target){
                       window.setTimeout(function () {
                           target.$el.find('textarea').focus();
                       },200);
                   });
               }
           }
      },

      label_texts_init: function(sender, params) {
        sender.$el.html( this.rowInstance.refs.label_texts.$el.html() );
      },

      when_init: function(sender, params) {
        sender.config.text = this.rowInstance.refs.when.$el.html();
      },

      where_init: function(sender, params) {
        sender.config.text = this.rowInstance.refs.where.$el.html();
      },

      form_content_init: function(sender, params) {
        // console.log( this.rowInstance.refs.form_content.$el.clone() )
        sender.$el.html( this.rowInstance.refs.form_content.$el.html() );
      },

      images_init: function(sender, params) {
        sender.$el.html( this.rowInstance.refs.images.$el.html() );

        var $images = sender.$el.find('.yy-image');
        var imgList = this.data.images.map(function(e, i) {
          return {src: e.fileKey, el: $images[i]};
        });

        sender.$el.on('click', '.yy-repeatitem', function(e) {
          photoswipe.showPhotoWall(imgList, $(e.currentTarget).index() );
        });
      },

      files_init: function(sender, params) {
        sender.$el.html( this.rowInstance.refs.files.$el.html() ).on('click', '[data-comname="file_download"]', function(e) {
          window.open( $(e.target).closest('.yy-repeatitem').attr('gotourl') );
        });
      },

      comment_textarea_keyup: function(sender, params) {
        var val = params.e.target.value;
        var res = val.replace(/回复[^:]+?:/, '').length + '/' + 200;
        this.pageview.refs.comment_textnumber.innerText.html(res).attr('title', res);
      },
      header_close_click:function(sender){
          sender.pageview.close();
      },
      getFileTypePath: function (file) {
        var path = "";
        var type = "";
        if (typeof file === "string") {
            type = file;
        } else {
            if (file.fileExtension && file.fileExtension.indexOf(".") === 0) {
                file.fileExtension = file.fileExtension.substring(1);
            }
            type = file.fileExtension;
        }
        if (type) {
            type = type.toLowerCase();
        }
        switch (type) {
            case "zip":
            case "rar":
            case "tar":
                path = "./imgs/zip_file.png";
                break;
            case "txt":
                path = "./imgs/txt_file.png";
                break;
            case "png":
            case "jpeg":
            case "jpg":
            case "gif":
                path = "./imgs/image_file.png";
                break;
            case "xls":
            case "xlsx":
                path = "./imgs/excel.png";
                break;
            case "doc":
            case "docx":
                path = "./imgs/word_file.png";
                break;
            case "ppt":
            case "pptx":
                path = "./imgs/ppt_file.png";
                break;
            case "pdf":
                path = "./imgs/pdf_file.png";
                break;
            case "mp4":
            case "avi":
            case "flv":
                path = "./imgs/video.png";
                break;
            default:
                path = "./imgs/file.png";
                break;
        }
        return path;
      },

      good_avatar_imgerror: function(sender) {
        setTimeout(function() {
          var data = sender.parent.components.good_name.datasource || {};
          sender.$el.html(function() {
            return ['<div class="yy-icon-img">',
                      '<div style="width: 30px; height: 30px; line-height: 30px; font-size: 12px; overflow: hidden; color: #fff; border-radius: 100%; background: ', getbg(data.name),'">', getTitle(data.name), '</div>',
                    '</div>'].join('');
          });
        }, 200);
      },

      row_img_imgerror: function(sender) {
        setTimeout(function() {
          var data = sender.rowInstance.components[1].datasource || {};
          sender.$el.html(function() {
            return ['<div class="yy-icon-img">',
                      '<div style="width: 30px; height: 30px; line-height: 30px; font-size: 12px; overflow: hidden; color: #fff; border-radius: 100%; background: ', getbg(data.name),'">', getTitle(data.name), '</div>',
                    '</div>'].join('');
          });
        }, 200);
      },
      comment_list_init: function(sender){
        sender.config.ajaxConfig = {
          type: 'GET',
          url: '/diaryComment/' + this.data.id + '/reply',
          pageNumKey: 'pageNum',
          pageSize: 30,
          data: {
              pageNum: 1,
              pageSize: 30
          }
        };
      },

      comment_list_didmount: function (sender, params) {
          sender.loadFirstPageData();
      },

      comment_list_parsedata: function(sender, params) {
        if( params.data.code !== 0 ){
          return false;
        }

        var self = this;
        var res = params.data.data.replyList.map(function(e) {
          return {
            avatar: e.user.headImgUrl + '.thumb.jpg',
            name: e.user.userName,
            rname: e.replyUserName ? ' 回复 ' + e.replyUserName : '',
            createTime: utils.timestampToTimeStr(e.createTime),
            content: e.content.replace(/\n/g, "<br/>"),
            reply_btn_text: e.userId === self.userInfo.id ? '删除' : '回复',
            rid: e.id,
            uid: e.userId
          };
        });
        return {data: res, sumCount: 0};
      },

      comment_okbtn_click: function(sender) {
        var self = this;
        var val = sender.pageview.refs.comment_textarea.getValue().replace(/^回复[^:]+?:/, '');
        if(!val) {
          sender.pageview.showTip({
            text: '回复不能为空!',
            duration: 2000
          });
          return;
        }
        // val = JSON.stringify(val);
        var data = {
          diaryId: this.data.id,
          replySource: 3,
          content: val
        };

        if(this.rdata) {
          data.replyCommentId = this.rdata.rid;
          data.replyUserName = this.rdata.name;
        }
        this.pageview.ajax({
          url: '/diaryComment/reply',
          type: 'POST',
          data: data,
          success: function(res) {
            self.rowInstance.datasource.commentNum ++;
            self.rowInstance.rebind(self.rowInstance.datasource);
            sender.pageview.refs.comment_textarea.setValue('');
            sender.pageview.refs.comment_list.loadFirstPageData();
            self.pageview.refs.comment_textnumber.innerText.html('0/200').attr('title', res);
          }
        });
      },
    collect_btn_init: function(sender, params) {

      if(this.data.favorite.isFavorite) {
        sender.selected();
        sender.isSelected = true;
      } else {
        sender.unSelected();
        sender.isSelected = false;
      }
    },
	 	collect_btn_click: function(sender, params) {
		  var _this = this;
      var url = '/favorite/add/';

		  if(sender.isSelected) {
			  // 取消收藏
        url = '/favorite/delete/';
		  } else {
			  // 收藏
		  }
		  this.pageview.ajax({
		      url: url,
		      type: 'POST',
          data:{diaryId:_this.data.id},
		      success: function(data) {
		          if(data.code === 0) {
		              if(sender.isSelected){
		                  //取消收藏
		                  sender.isSelected = false;
                          sender.unSelected();
                          _this.rowInstance.datasource.favorite.isFavorite = 0;
                          _this.rowInstance.datasource.favorite.favoriteNum--;

		              }
		              else {
		                  //收藏
		                  sender.isSelected = true;
    		              sender.selected();
                          _this.rowInstance.datasource.favorite.isFavorite = 1;
                          _this.rowInstance.datasource.favorite.favoriteNum++;
		              }
                      console.log(_this.rowInstance.datasource);
                  _this.rowInstance.rebind(_this.rowInstance.datasource);

		          }
		          // _this.pageview.hideSubmiting(data.code === 0);
		      },
		      error: function() {
		          // _this.pageview.hideSubmiting(false);
		      }
		  });
	  },
      like_btn_init: function(sender){
          if(this.data.isLike !== 0){
              sender.selected();
          }
          else{
              sender.unSelected();
          }
      },
      like_btn_click: function(sender){
          //点赞日志或取消点赞
          var _this = this;
          // this.pageview.showSubmiting({
          //     text:"正在处理中...",
          //     successText:null
          // });
          this.pageview.ajax({
              url: '/diaryLike/' + _this.data.id,
              type: 'POST',
              success: function(data) {
                  if(data.code === 0) {
                      if(sender.isSelected){
                          //取消点赞
                          _this.data.isLike = 0;
                          sender.unSelected();
                          _this.rowInstance.datasource.isLike = 0;
                          _this.rowInstance.datasource.like.isLike = 0;
                          _this.rowInstance.datasource.like.likeNum --;
                          _this.rowInstance.rebind(_this.rowInstance.datasource);
                          // _this.pageview.showTip({
                          //   text: '取消点赞成功',
                          //   duration: 1000
                          // });
                      }
                      else {
                          //点赞
                          _this.data.isLike = 1;
                          sender.selected();
                          _this.rowInstance.datasource.isLike = 1;
                          _this.rowInstance.datasource.like.isLike = 1;
                          _this.rowInstance.datasource.like.likeNum ++;
                          _this.rowInstance.rebind(_this.rowInstance.datasource);
                          // _this.pageview.showTip({
                          //   text: '点赞成功',
                          //   duration: 1000
                          // });
                      }

                      if(_this.pageview.refs.good_panel)
                        _this.good_panel_didmount( _this.pageview.refs.good_panel );
                  }
                  // _this.pageview.hideSubmiting(data.code === 0);
              },
              error: function() {
                  _this.pageview.hideSubmiting(false);
              }
          });

      },
      mainvlayout_click:function() {
          this.more_popup.$el.addClass("displaynone");
      },
      more_popup_init:function(sender){
          this.more_popup = sender;
      },
      more_edit_click:function(sender){
          if(this.more_popup.$el.hasClass("displaynone")){
              this.more_popup.$el.removeClass("displaynone");
          }else{
              this.more_popup.$el.addClass("displaynone");
          }

      },
      print_btn_click:function(sender){
            //打印
          window.print();
      },
      edit_btn_click:function(sender){
          //跳转编辑
          var _this = this;
          sender.pageview.close();
          this.pageview.config.ownerPage.pageview.showPage({
              pageKey: "add",
              mode: "slide",
              params: {data: _this.data}
          });
      },
      del_dialog_cancelbtn_click:function(){
        this.pageview.hideDialog("del_dialog");
      },
      del_dialog_okbtn_click:function(sender){
        this.pageview.hideDialog("del_dialog");
        var _this = this;
        this.pageview.showSubmiting({
            text:"正在处理中...",
            successText:null
        });
        this.pageview.ajax({
            url: '/diary/' + _this.data.id,
            type: 'DELETE',
            success: function(data) {
                if(data.code === 0) {
                    _this.pageview.showTip({
                        text: '删除日志成功',
                        duration: 1000
                    });


                    sender.pageview.close();
                    _this.rowInstance.remove();
                }
                _this.pageview.hideSubmiting(data.code === 0);
            },
            error: function() {
                _this.pageview.hideSubmiting(false);
            }
        });
      },
      delete_btn_click:function(sender){
        this.pageview.showDialog("del_dialog");
          //删除日志

      },
      row_reply_btn_click: function(sender) {
        this.rdata = sender.datasource;
        // console.log(this.rdata)
        if(sender.datasource.uid == this.userInfo.id) {
          this.preDeleteCommentId = sender.datasource.id;
          this.pageview.showDialog('del_comment_dialog');
        } else {
          this.currentComment = sender.datasource;
          var text = '回复' + this.currentComment.name + ':';
          this.currentCommentText = text;
          this.pageview.refs.comment_textarea.setValue(text);
          this.pageview.refs.comment_textarea.focus();
        }
      },

      del_comment_dialog_cancelbtn_click: function() {
        this.pageview.hideDialog('del_comment_dialog');
      },

      del_comment_dialog_okbtn_click: function(sender) {
        this.pageview.hideDialog('del_comment_dialog');
        var self = this;
        this.pageview.showSubmiting({
          text: '正在删除',
          successText: null
        });
        this.pageview.ajax({
          url: '/diaryComment/delete/' + this.rdata.rid,
          type: 'DELETE',
          success: function(res) {
              if(res.code === 0) {
                self.pageview.refs.comment_list.loadFirstPageData();
              }
              self.pageview.hideSubmiting(res.code === 0);
          },
          error: function() {
            self.pageview.hideSubmiting(false);
          }
        });
      },


      good_panel_didmount: function(sender, params) {
        this.pageview.ajax({
          url: "/diaryLike/getDiaryLikeList",
          type: "GET",
          data:{
            id: this.data.id
          },
          success: function(res) {
            if(res.code === 0) {
              if(res.data.diaryLike.length) {
                var ret = res.data.diaryLike.map(function(e, i) {
                  return {
                    avatar: e.avatar + '.thumb.jpg',
                    name: e.userName
                  };
                });

                // ret = [{
                //   avatar: 'http://115.29.39.62/task/web/img/default_avatar.thumb.jpg',
                //   name: '乔布斯'
                // }];
                sender.bindData( ret );
              } else {
                sender.bindData( [] );
              }
            }
          }
        });
      },

      record_panel_didmount: function(sender, params) {
        this.pageview.ajax({
          url: '/diaryOpeationLoggers/' + this.data.id,
          type: 'GET',
          success: function(res) {
            if(res.code === 0) {
              var ret = res.data.map(function(e, i) {
                return {
                  avatar: e.avatar ? e.avatar : "./imgs/header.png",
                  name: e.userName,
                  time: utils.timestampToTimeStr(e.createTime),
                  des: e.reason
                };
              });

              // ret = [{
              //   headImgUrl: 'http://115.29.39.62/task/web/img/default_avatar.thumb.jpg',
              //   name: 'steve jobs',
              //   time: '3分钟前',
              //   des: '林玲 将任务名称修改为 “企业空间3.0-任务轻应用交互设计”的操作'
              // }]

              sender.bindData(ret);
            }

          }
        });

      },


      segement_didmount:function(sender){
        sender.components[0].select();
      },
      segement_itemclick:function(sender, params){
        sender.select();
        if(params.index===0){
          this.pageview.refs.segment_status.changeStatus("reply_wrap");
        }else if(params.index===1){
          this.pageview.refs.segment_status.changeStatus("good_wrap");
        }else if(params.index===2){
          this.pageview.refs.segment_status.changeStatus("record_wrap");
        }
      },


      range_icon_init:function(sender){
        if(this.data.visibleRange===1&&this.isMY&&this.data.range.length>0){

        } else {
            sender.config.style.display = "none";
        }

      },

      range_dialog_header_close_click: function(sender){
        this.pageview.hideDialog("range_dialog");
      },
      range_icon_click: function(sender,params){
        this.curRowData = sender.datasource;
        this.pageview.showDialog("range_dialog");
      },
      rangetree_init: function(sender){
        sender.config.range = this.data.range;
      },
      onPageBeforeClose:function(){
          // debugger;
          // this.rowInstance.datasource.userName = "sdsdasdadasda";
          // this.rowInstance.rebind(this.rowInstance.datasource);
      }
    };
    return pageLogic;
});
